package com.mcrmb;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

public class CommandListen {
    //private PointSystem plugin;
    private List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();
    public static FileConfiguration configs = Mcrmb.configs;//配置集合
    //public static Player SenderPlayer;
    public static String wname;//玩家名
    public static String use;//用途
    public static String money;//钱数
    public static String[] s_a;//参数个数
    public static String cnum;
    public static String cpwd;
    public static String ctype;
    public static String username;

    public static String sid = configs.getString("sid");//服务器sid
    public static String key = configs.getString("key");//服务器key
    public static String point = configs.getString("point");//单位名称
    public static String prefix = configs.getString("prefix");//插件前缀
    public static String api = "http://www.mcrmb.com/Api/";
    public static String help = configs.getString("help");//帮助说明
    public static boolean logapi = configs.getBoolean("logapi");//是否记录api操作
    //public static boolean showpay = configs.getBoolean("showpay");//是否公屏展示玩家购买?
    public static String command_word = configs.getString("command");
    private static Misc m = new Misc();
    private static Json json = new Json();
    private static CommandSender s;
    private static String sign;

    /*public CommandListen(PointSystem plugin) {//plugin对象传送,在CommandListen初始化时
        //System.out.println("前缀:"+PointSystem.configs.getString("prefix"));
        //this.plugin = plugin;
        //configs = plugin.configs;
    }*/

    public boolean commands(CommandSender sender, Command command, String label, String[] args) {
        // Param pa = new Param();
        if (label.equalsIgnoreCase(command_word)) {
            if ((sender instanceof Player)) {//前后台检测,当前为前台
                wname = sender.getName();//获取玩家名
                s = sender;
            } else {//后台指令集
                sender.sendMessage("§c" + prefix + "请不要在后台输入 /"+command_word+" 命令！");
                return true;
            }

            if (args.length == 0) {//第一参数检测, 没有第一参数则显示帮助.
                s.sendMessage(help.replace("<br>", "\n").replace("{command}",command_word));//发送帮助信息
                return true;
            }


            if (args[0].equalsIgnoreCase("cx")) {//查询流水接口**************************************************************************
                try {
                    sign = m.getMD5(sid + wname + key);

                    s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                    new Thread(new Runnable() {
                        public void run() {
                            if (logapi) {
                                System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:CheckRecord?sign=" + sign + "&sid=" + sid + "&wname=" + wname);
                            }
                            String result = "";
                            ArrayList arr = json.Json2Array(api + "CheckRecord?sign=" + sign + "&sid=" + sid + "&wname=" + wname);//json已经转为arr

                            s.sendMessage("§b==============================================================");
                            if (arr.size() > 2) {//有data内容!
                                JSONArray json_data = (JSONArray) arr.get(2);
                                result = prefix + "为您查询到以下流水记录：\n【时间】           【金额】 【说明】\n";
                                for (int i = 0; i < json_data.length(); i++) {
                                    JSONObject j = json_data.getJSONObject(i);
                                    result = result + "【" + m.StampToTime(j.get("date").toString()) + "】【" + j.get("money") + "】【" + j.get("text") + "】\n";
                                }
                                s.sendMessage(result + "§b仅显示最新5条，如需查询所有记录，请登陆 http://www.mcrmb.com/");
                                //return true;
                            } else {
                                if (arr.get(0).equals("404") || arr.get(0).equals("444")) {
                                    s.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                                    System.out.println("[MCRMB] " + arr.get(1).toString());//服主界面显示原因
                                    //return true;
                                } else {
                                    s.sendMessage(prefix + arr.get(1).toString());//获取arr中的msg
                                    //return true;
                                }
                            }
                            s.sendMessage("§b==============================================================");
                        }
                    }).start();
                    return true;


                } catch (Exception e) {
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }
            } else if (args[0].equalsIgnoreCase("ck")) {//查卡接口**************************************************************************
                try {
                    s_a = args;
                    s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                    new Thread(new Runnable() {
                        public void run() {
                            ArrayList arr;
                            String result = "";
                            //执行远程操作起点
                            if (s_a.length > 1) {//有卡号
                                String cnum = s_a[1];
                                String sign = m.getMD5(sid + wname + cnum + key);
                                if (logapi) {
                                    System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:CheckCard?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&cnum=" + cnum);
                                }
                                arr = json.Json2Array(api + "CheckCard?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&cnum=" + cnum);//json已经转为arr
                            } else {
                                String sign = m.getMD5(sid + wname + key);
                                if (logapi) {
                                    System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:CheckCard?sign=" + sign + "&sid=" + sid + "&wname=" + wname);
                                }
                                arr = json.Json2Array(api + "CheckCard?sign=" + sign + "&sid=" + sid + "&wname=" + wname);//json已经转为arr
                            }
                            s.sendMessage("§b==============================================================");
                            if (arr.size() > 2) {//有data内容!
                                JSONArray json_data = (JSONArray) arr.get(2);
                                result = prefix + "为您查询到以下充值卡记录：\n【时间】             【卡号】      【成功金额】 【状态】\n";
                                for (int i = 0; i < json_data.length(); i++) {
                                    JSONObject j = json_data.getJSONObject(i);
                                    result = result + "【" + m.StampToTime(j.get("date").toString()) + "】【" + j.get("num") + "】【" + j.get("money") + "】【" + m.CardStatus(j.get("status").toString()) + "】\n";
                                }
                                s.sendMessage(result + "§b仅显示最新5条，如需查询所有记录，请登陆 http://www.mcrmb.com/");
                                //return true;
                            } else {
                                if (arr.get(0).equals("404") || arr.get(0).equals("444")) {
                                    s.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                                    System.out.println("[MCRMB] " + arr.get(1).toString());//服主界面显示原因
                                    //return true;
                                } else {
                                    s.sendMessage(prefix + "查不到记录,查询的卡号没有提交过/玩家未曾充值过!");//获取arr中的msg
                                    //return true;
                                }
                            }
                            s.sendMessage("§b==============================================================");
                            //执行远程操作终点
                        }
                    }).start();
                    return true;

                } catch (Exception e) {
                    //System.out.println(e.getMessage());
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }
            } else if (args[0].equalsIgnoreCase("cz")) {//充值操作接口**************************************************************************
                try {
                    if (args.length == 4) {//必须先有4个参数
                        String typelow = args[1].toLowerCase();
                        cnum = args[2];
                        cpwd = args[3];
                        if (typelow.equals("yd")) {
                            ctype = "1";
                            if (cnum.length() != 17 || cpwd.length() != 18) {
                                sender.sendMessage(prefix + "卡号或密码长度不对! 移动卡卡号(序列号)为17位, 密码为18位.");
                                sender.sendMessage(prefix + "您输入的【移动卡】卡号为【" + cnum.length() + "位】, 密码为【" + cpwd.length() + "位】.");
                                return true;
                            }
                        } else if (typelow.equals("lt")) {
                            ctype = "2";
                            if (cnum.length() != 15 || cpwd.length() != 19) {
                                sender.sendMessage(prefix + "卡号或密码长度不对! 联通卡卡号(序列号)为15位, 密码为19位.");
                                sender.sendMessage(prefix + "您输入的【联通卡】卡号为【" + cnum.length() + "位】, 密码为【" + cpwd.length() + "位】.");
                                return true;
                            }
                        } else if (typelow.equals("dx")) {
                            ctype = "3";
                            if (cnum.length() != 19 || cpwd.length() != 18) {
                                sender.sendMessage(prefix + "卡号或密码长度不对! 电信卡卡号(序列号)为19位, 密码为18位.");
                                sender.sendMessage(prefix + "您输入的【电信卡】卡号为【" + cnum.length() + "位】, 密码为【" + cpwd.length() + "位】.");
                                return true;
                            }
                        } else {
                            sender.sendMessage(prefix + "卡类型错误! 移动请打yd, 联通请打lt, 电信请打dx\n" + prefix + "充值操作正确姿势:/"+command_word+" cz <类型> <卡号> <卡密>");
                            return true;
                        }

                        sign = m.getMD5(sid + wname + ctype + cnum + cpwd + key);//签名获得

                        s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                        new Thread(new Runnable() {
                            public void run() {
                                if (logapi) {
                                    System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:Charge?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&ctype=" + ctype + "&cnum=" + cnum + "&cpwd=" + cpwd);
                                }
                                ArrayList arr = json.Json2Array(api + "Charge?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&ctype=" + ctype + "&cnum=" + cnum + "&cpwd=" + cpwd);//json已经转为arr
                                s.sendMessage("§b==============================================================");
                                Object code = arr.get(0);
                                Object msg = arr.get(1);
                                if (code.equals("555")) {
                                    s.sendMessage(prefix + "提交接口返回错误:" + msg);
                                    // return true;
                                } else if (code.equals("404") || code.equals("444")) {
                                    s.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                                    System.out.println("[MCRMB] " + msg.toString());//服主界面显示原因
                                    //return true;
                                } else if (code.equals("101")) {
                                    s.sendMessage(prefix + "已为您开户并成功提交卡密! \n" + prefix + "请稍候输入/"+command_word+" ck查询结果,也可以输入/"+command_word+" money查询余额");
                                    //return true;
                                } else if (code.equals("201")) {
                                    s.sendMessage(prefix + "已为您成功提交卡密! \n" + prefix + "请稍候输入/"+command_word+" ck查询结果,也可以输入/"+command_word+" money查询余额");
                                    //return true;
                                } else if (code.equals("102")) {
                                    JSONArray json_data = (JSONArray) arr.get(2);
                                    s.sendMessage(prefix + "已为您开户,但卡密提交失败!请检查!\n" + prefix + "原因:" + m.CardStatus(json_data.getJSONObject(0).get("wmsg").toString()));
                                    //return true;
                                } else if (code.equals("202")) {
                                    JSONArray json_data = (JSONArray) arr.get(2);
                                    s.sendMessage(prefix + "卡密提交失败! 请检查! 原因: " + m.CardStatus(json_data.getJSONObject(0).get("wcode").toString()));
                                    // return true;
                                } else if (code.equals("105")) {
                                    s.sendMessage(prefix + "卡号和密码必须都是数字!");
                                    // return true;
                                }
                                s.sendMessage("§b==============================================================");
                                //执行远程操作终点
                            }
                        }).start();
                        return true;


                    } else {
                        sender.sendMessage(prefix + "充值操作正确姿势:/"+command_word+" cz <类型> <卡号> <卡密>\n" + prefix + "类型支持: 移动请打yd, 联通请打lt, 电信请打dx\n" + prefix + "§c注意: 卡号和密码里都不要出现空格! 谢谢配合!");
                        return true;
                    }
                } catch (Exception e) {
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }
            } else if (args[0].equalsIgnoreCase("money")) {//查询余额接口**************************************************************************
                try {//执行远程操作起点


                    sign = m.getMD5(sid + wname + key);
                    s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                    new Thread(new Runnable() {
                        public void run() {
                            if (logapi) {
                                System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:CheckMoney?sign=" + sign + "&sid=" + sid + "&wname=" + wname);
                            }
                            ArrayList arr = json.Json2Array(api + "CheckMoney?sign=" + sign + "&sid=" + sid + "&wname=" + wname);//json已经转为arr
                            s.sendMessage("§b==============================================================");
                            if (arr.get(0).equals("101")) {
                                //有数据
                                JSONArray json_data = (JSONArray) arr.get(2);
                                JSONObject j = json_data.getJSONObject(0);
                                s.sendMessage(prefix + "玩家: " + wname + "\n" + prefix + "您的余额: " + j.get("money") + point + "\n" + prefix + "历史消费: " + j.get("allpay") + point + "\n" + prefix + "历史充值: " + j.get("allcharge") + point);
                                //return true;
                            } else if (arr.get(0).equals("102")) {
                                s.sendMessage(prefix + "您尚未开户,请提交充值卡以便自动开户!");
                                //return true;
                            }
                            s.sendMessage("§b==============================================================");
                        }
                    }).start();
                    return true;


                } catch (Exception e) {
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }
            } else if (args[0].equalsIgnoreCase("bd")) {//绑定接口**************************************************************************
                try {
                    //String username;
                    if (args.length < 2) {
                        sender.sendMessage(prefix + "绑定用户正确姿势:/"+command_word+" bd <你的用户名>\n" + prefix + "注意,用户名请在 http://www.mcrmb.com 注册!");
                        return true;
                    } else if (args.length == 3) {//执行远程操作起点

                        username = args[1];
                        sign = m.getMD5(sid + wname + username + key);

                        s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                        new Thread(new Runnable() {
                            public void run() {
                                if (logapi) {
                                    System.out.println("[MCRMB] 玩家" + wname + "发起接口请求:Bid?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&username=" + username);
                                }
                                ArrayList arr = json.Json2Array(api + "Bid?sign=" + sign + "&sid=" + sid + "&wname=" + wname + "&username=" + username);//json已经转为arr
                                s.sendMessage("§b==============================================================");
                                s.sendMessage(prefix + arr.get(1).toString());
                                s.sendMessage("§b==============================================================");
                            }
                        }).start();
                        return true;


                    } else {
                        username = args[1];
                        sender.sendMessage(prefix + "一旦绑定无法解绑,请输入/"+command_word+" bd " + username + " sure 来确认绑定!");
                    }
                } catch (Exception e) {
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }
            } else {
                s.sendMessage(help.replace("<br>", "\n").replace("{command}",command_word));//发送帮助信息
            }
//玩家指令结束*******************************************************************************************************************************************************


        } else if (label.equalsIgnoreCase(command_word+"admin") && sender.hasPermission("Mcrmb.admin")) {
            s = sender;
            if (args.length == 0) {//第一参数检测, 没有第一参数则显示帮助.
                sender.sendMessage(prefix + "管理员指令:");
                sender.sendMessage(prefix + "/"+command_word+"admin reload 重载插件配置.");
                sender.sendMessage(prefix + "/"+command_word+"admin xf <玩家名> <金额> <用途> 强制消费指令,需手动发奖励哦.");
                sender.sendMessage(prefix + "/"+command_word+"admin money <玩家名> 查询玩家的余额信息.");
                sender.sendMessage(prefix + "当前服务器SID: " + sid);
                sender.sendMessage(prefix + "当前服务器key: " + key + "(请勿外泄!)");
                sender.sendMessage(prefix + "当前单位: " + point);//发送帮助信息
                return true;
            }

            if (args[0].equalsIgnoreCase("xf")) {//消费接口测试
//                listData= pa.paramhistory(PointSystem.plugin.getConfig().getString("serverid"),SenderPlayer.getName());
                if (args.length == 4) {
                    wname = args[1];
                    money = args[2];
                    use = args[3];

                    s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                    new Thread(new Runnable() {
                        public void run() {
                            boolean xf = new PayApi().Pay(wname, money, use, false);//玩家名,钱(转了String),用途,否公屏
                            s.sendMessage("§b==============================================================");
                            s.sendMessage(prefix + "接口方式消费操作已执行，扣除返回结果：" + xf + "！");
                            s.sendMessage("§b==============================================================");
                        }
                    }).start();
                    return true;

                } else {
                    sender.sendMessage(prefix + "参数不足，示例：/"+command_word+"admin xf <玩家名> <金额> <用途>");
                    return true;
                }
            } else if (args[0].equalsIgnoreCase("money")) {//查询玩家的余额
                try {
                    if (args.length == 2) {
                        wname = args[1];
                        sign = m.getMD5(sid + wname + key);

                        s.sendMessage(prefix + "§a指令已成功发送！  请耐心等待。");
                        new Thread(new Runnable() {
                            public void run() {
                                if (logapi) {
                                    System.out.println("[MCRMB] 发起接口请求:CheckMoney?sign=" + sign + "&sid=" + sid + "&wname=" + wname);
                                }
                                ArrayList arr = json.Json2Array(api + "CheckMoney?sign=" + sign + "&sid=" + sid + "&wname=" + wname);//json已经转为arr
                                s.sendMessage("§b==============================================================");
                                if (arr.get(0).equals("101")) {
                                    //有数据
                                    JSONArray json_data = (JSONArray) arr.get(2);
                                    JSONObject j = json_data.getJSONObject(0);
                                    s.sendMessage(prefix + "玩家: " + wname);
                                    s.sendMessage(prefix + "余额: " + j.get("money") + point);
                                    s.sendMessage(prefix + "历史消费: " + j.get("allpay") + point);
                                    s.sendMessage(prefix + "历史充值: " + j.get("allcharge") + point);
                                } else if (arr.get(0).equals("102")) {
                                    s.sendMessage(prefix + "该玩家" + wname + "尚未开户!");
                                }
                                s.sendMessage("§b==============================================================");
                            }
                        }).start();
                        return true;

                        /*ArrayList arr = json.Json2Array(api + "CheckMoney?sign=" + sign + "&sid=" + sid + "&wname=" + wname);//json已经转为arr
                        if (arr.get(0).equals("101")) {
                            //有数据
                            JSONArray json_data = (JSONArray) arr.get(2);
                            JSONObject j = json_data.getJSONObject(0);
                            sender.sendMessage(prefix + "玩家: " + wname );
                            sender.sendMessage(prefix + "余额: " + j.get("money") + point);
                            sender.sendMessage(prefix + "历史消费: " + j.get("allpay") + point);
                            sender.sendMessage(prefix + "历史充值: " + j.get("allcharge") + point);
                            return true;
                        } else if (arr.get(0).equals("102")) {
                            sender.sendMessage(prefix + "该玩家尚未开户!");
                            return true;
                        }*/
                    } else {
                        sender.sendMessage(prefix + "参数数量不足，示例：/"+command_word+"admin money <玩家名>");
                        return true;
                    }
                } catch (Exception e) {
                    sender.sendMessage(prefix + "操作失败，建议您联系服主咨询！");
                    System.out.println("[MCRMB] 访问接口异常!");
                    return true;
                }

            } else if (args[0].equalsIgnoreCase("reload")) {
                Mcrmb.plugin.reload();
                configs = Mcrmb.configs;
                sid = configs.getString("sid");//服务器sid
                key = configs.getString("key");//服务器key
                point = configs.getString("point");//单位名称
                prefix = configs.getString("prefix");//插件前缀
                help = configs.getString("help");//帮助说明
                logapi = configs.getBoolean("logapi");//是否记录api操作
                System.out.println("[MCRMB] 已经重新载入配置!");
                return true;
            } /*else if (args[0].equalsIgnoreCase("cx")) {
                String result = "";
                if (args.length == 2) {
                    List<Map<String, Object>> listData = pa.paramcheckrecord(PointSystem.plugin.getConfig().getString("sid"), args[1]);
                    if (!(listData.size() == 0)) {           //判断这个listData是否为无效的

                        result = "§6—————————————————————————交易记录—————————————————————————\n———————时间————————金额—————————用途—————————\n";
                        for (Map<String, Object> m : listData) {
                            for (String k : m.keySet()) {

                                result = result + "【" + m.get(k) + "】";

                            }
                            result += "\n";
                        }
                        sender.sendMessage(result + "\n" + "§r§2当前交易记录为最新的5条，http://daiding");
                        return true;
                    }
                } else {
                    sender.sendMessage("§c查询交易记录的参数不足");
                    return true;
                }
            }*/
        }
        return true;
    }

}
